import emitter from "../emitter";

const { ccclass, property } = cc._decorator;

@ccclass
export default class pfBulletEgg extends cc.Component {
    @property(cc.Node)
    jianDan: cc.Node = null;
    @property(cc.Node)
    egg: cc.Node = null;
    onLoad() {
        this.addEventListener();
        this.initData();
    }

    minPosi_y
    initData() {
        this.minPosi_y = -(cc.winSize.height / 2 + 500);
    }

    addEventListener() {
        emitter.emit("resetPlayerPosi", this.setEndPosi.bind(this));
        emitter.on("eggDestroy", this.stopEggMove.bind(this));
    }

    onDisable() {
        emitter.off("eggDestroy", this.stopEggMove.bind(this));
    }

    //设置鸡蛋状态 鸡蛋=>煎蛋
    stopEggMove(nodeEgg: cc.Node) {
        let eggItem = nodeEgg.getComponent("pfBulletEgg");
        let disPos = nodeEgg.position.normalizeSelf();
        disPos.divSelf(5);
        eggItem.posData = disPos;
        eggItem.egg.active = false;
        eggItem.isMove = false;
        eggItem.jianDan.runAction(cc.fadeIn(0.2));

        this.scheduleOnce(() => {
            //从父节点移除 并重置数据
            if (!eggItem.node) return
            eggItem.egg.active = true;
            eggItem.jianDan.opacity = 0;
            eggItem.isMove = true;
            nodeEgg.removeFromParent();
            emitter.emit("putEnemyBullet", nodeEgg);
        }, 0.4);
    }

    posData;
    isMove = false;
    setEndPosi(posi) {
        let endPosi = this.node.parent.convertToNodeSpaceAR(posi);
        if (endPosi.y >= this.node.y) endPosi.y = this.node.y - 400;
        let disPos = endPosi.normalizeSelf();
        disPos.divSelf(0.2);
        this.posData = disPos;
        this.isMove = true;
    }

    update() {
        if (this.isMove && !this.posData) {
            emitter.emit("resetPlayerPosi", this.setEndPosi.bind(this));
            return
        }
        this.node.setPosition(this.node.position.add(this.posData));
        if (this.node.y < this.minPosi_y) {
            this.posData = null;
            // this.node.destroy();
            emitter.emit("putEnemyBullet", this.node)
        }
    }
}
